<?php
namespace app\common\exception;

use think\exception\Handle;
use think\facade\Log;
use think\Response;
use Throwable;
use Exception;

class ExceptionHandler  extends Handle
{
    private $code;
    private $msg;

    public function render($request, Throwable $e): Response
    {
        if($e instanceof BaseException){
            $this->code = $e->code;
            $this->msg = $e->msg;
        }else{
            if (env('APP_DEBUG', '0')){
                return parent::render($request, $e);
            } else {
                $this->code = 500;
                $this->msg = '服务器错误,请联系客服或者稍后再试';
//                $this->recordErrorLog($e);
            }
        }
        $result = [
            'code' => $this->code,
            'msg' => $this->msg
        ];
        return  $this->json($result);
    }
    //记录日志
    public function recordErrorLog(Exception $e){
        Log::record($e->getMessage(),'error');
    }

    public function json($data) {
        return json($data);
    }
}